#include "testloading.h"
#include "ui_testloading.h"
#include <QtMath>

TestLoading::TestLoading(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TestLoading)
{
    ui->setupUi(this);

    progressTimer = new QTimer(this);
    progressTimer->setInterval(1000);

    setAttribute(Qt::WA_TranslucentBackground, true);
    this->setWindowFlags(this->windowFlags() | Qt::SubWindow);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget->setGraphicsEffect(shadow);
    if (windowWidth >= 1280) {
        this->setProperty("cssSize", "large");
    }

    connect(progressTimer, &QTimer::timeout, this, &TestLoading::updateProgressSlot);
}

TestLoading::~TestLoading()
{
    delete ui;
}

void TestLoading::updateTips(const QString &tip)
{
    ui->lblDynamicTips->setText(tip);
}

void TestLoading::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

/**
 * @brief TestLoading::start
 * @param title 加载框标题
 * @param timeTotal
 */
/**
 * @brief TestLoading::start 展示加载框
 * @param timeTotal 倒计时，单位：s
 * @param title 标题
 * @param tip 提示
 */
void TestLoading::start(int timeTotal, const QString &title, const QString &tip)
{
    this->timeTotal = timeTotal;
    progressVal = 0;
    ui->lblTitle->setText(title);
    ui->lblDynamicTips->setText(tip);
    ui->sliderProgress->setMaximum(timeTotal * 100);
    ui->sliderProgress->setValue(0);
    ui->lblPercentage->setText("0%");
    QWidget::show();
    progressTimer->start();
}

/**
 * @brief TestLoading::stop 关闭加载框
 */
void TestLoading::stop()
{
    QWidget::hide();
    progressTimer->stop();
}

void TestLoading::updateProgressSlot()
{
    if (progressVal + 100 >= timeTotal * 100) {
        // 预计时间已到
        progressVal = timeTotal * 100 - 1;
        progressTimer->stop();
    } else {
        progressVal += 100;
    }
    ui->sliderProgress->setValue(progressVal);
    int progressPercentage = qFloor(progressVal / timeTotal);
    ui->lblPercentage->setText(QString("%1%").arg(progressPercentage));
}
